package com.mvvm.start

import AppConfig.baseUrl
import AppConfig.baseUrlTest
import android.content.pm.PackageManager
import android.os.SystemClock
import com.mvvm.start.base.BaseApplication
import com.mvvm.start.base.utils.ConstantUtils
import com.mvvm.start.base.utils.SPUtils
import com.mvvm.start.base.utils.toast


/**
 * @author
 * @功能:
 * @Creat 12/10/20 4:51 PM
 * @Compony 465008238@qq.com
 */
class Application : BaseApplication() {
    private var counts = LongArray(5)

    /**
     * 点击5次显示渠道号
     */
    fun showChannelNumber() {
        System.arraycopy(
            counts, 1, counts, 0,
            counts.size - 1
        )
        //源数组  源数组要复制的起始位置 目的数组  目的数组放置的起始位置  复制的长度
        counts[(counts.size - 1)] = SystemClock.uptimeMillis()
        if (counts[0] > SystemClock.uptimeMillis() - 1500) {
            "当前渠道号:${getChannelName()}".toast()
        }
    }

    /**
     * 获取友盟渠道名
     * @return 如果没有获取成功，那么返回值为空
     */
    fun getChannelName(): String {
        var channelName = "1"
        try {
            val packageManager = BaseApplication.application.packageManager
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                val applicationInfo =
                    packageManager.getApplicationInfo(
                        BaseApplication.application.packageName,
                        PackageManager.GET_META_DATA
                    )
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //此处这样写的目的是为了在debug模式下也能获取到渠道号，如果用getString的话只能在Release下获取到。
                        channelName = applicationInfo.metaData["UMENG_CHANNEL"].toString() + ""
                    }
                }
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return channelName
    }


    /**
     * 点击5次显切换服务器地址
     */
    fun setTestUrl() {
        System.arraycopy(
            counts, 1, counts, 0,
            counts.size - 1
        )
        //源数组  源数组要复制的起始位置 目的数组  目的数组放置的起始位置  复制的长度
        counts[(counts.size - 1)] = SystemClock.uptimeMillis()
        if (counts[0] > SystemClock.uptimeMillis() - 1500) {
            (SPUtils.getInstance(this).put(
                ConstantUtils.OPEN_TEST_URL,
                !(SPUtils.getInstance(this)
                    .getSharedPreference(ConstantUtils.OPEN_TEST_URL, false) as Boolean)
            ))
            isTestUrl = (SPUtils.getInstance(this)
                .getSharedPreference(ConstantUtils.OPEN_TEST_URL, false) as Boolean) //是否使用测试服地址
            "服务器地址已经切换为：[${if (isTestUrl) baseUrlTest else baseUrl}]重启即可生效".toast()
        }
    }

}



